package com.example.medicalzb.service;

import com.example.medicalzb.domain.Sale;
import com.example.medicalzb.entity.DrugEntity;
import com.example.medicalzb.entity.SaleEntity;
import com.example.medicalzb.mapper.DrugMapper;
import com.example.medicalzb.mapper.SaleMapper;
import com.example.medicalzb.model.DrugModel;
import com.example.medicalzb.util.Msg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SaleService {
    @Autowired
    private SaleMapper saleMapper;
    @Autowired
    private DrugMapper drugMapper;
    public PageInfo<Sale> getSaleWithPage(Integer pn, Integer size, String name) {
        if (pn == null){
            pn = 1;
        }
        if (size == null){
            size = 0;
        }
        PageHelper.startPage(pn,size);
        List<Sale> list = saleMapper.getAllSale(name);
        PageInfo<Sale> pageInfo = new PageInfo<>(list,5);
        return pageInfo;
    }

    public Msg getSaleById(Integer id) {
        Sale sale = saleMapper.getSaleById(id);
        if (sale != null){
            return Msg.success().data("sale",sale);
        }
        return Msg.fail().mess("没有找到该药店");
    }

    public Msg saveSale(Sale sale) {
        sale.setCreatetime(new DateTime().toDate());
        sale.setUpdatetime(new DateTime().toDate());
        SaleEntity saleEntity = new SaleEntity();
        BeanUtils.copyProperties(sale,saleEntity);
        int i = saleMapper.saveSale(saleEntity);
        if (i > 0){
            Long num = saleEntity.getTotal() % 5 == 0 ? (saleEntity.getTotal() / 5) : ((saleEntity.getTotal() / 5) + 1);
            return Msg.success().data("pages",num).mess("添加药店成功");
        }
        return Msg.fail().mess("添加药店失败");
    }

    public Msg updateSale(Long id, Sale sale) {
        sale.setUpdatetime(new DateTime().toDate());
        sale.setSaleId(id);
        SaleEntity saleEntity = new SaleEntity();
        BeanUtils.copyProperties(sale,saleEntity);
        int i = saleMapper.updateSale(saleEntity);
        System.out.println(i);
        if (i > 0){
            return Msg.success().mess("修改药店信息成功");
        }
        return Msg.fail().mess("修改药店信息失败");
    }

    public Msg deleteSale(Long id) {
        int i = saleMapper.deleteSale(id);
        List<DrugModel> allDrug = drugMapper.getAllDrug(null);
        for (DrugModel drugModel: allDrug){
            if (drugModel.getDrugSales().size() == 0){
                drugMapper.deleteDrugById(drugModel.getDrugId());
            }
        }
        if (i > 0){
            return Msg.success().mess("删除药店成功");
        }
        return Msg.fail().mess("删除药店失败");
    }
}
